//
//  ICChatViewController+Logic.m
//  ICome
//
//  Created by zhangrongwu on 2017/1/5.
//  Copyright © 2017年 iCom. All rights reserved.
//

#import "ICChatViewController+Logic.h"
#import "ICGroupUser.h"
#import "ICShareBottomView.h"
#import "ICVideoManager.h"
#import "ICChatNetworkManager.h"
#import "ICShareSuccessView.h"
#import "ICChatViewController+Event.h"
#import "ICFileTool.h"
#import "ICRedPacketNetworkManager.h"
#import "ICClickRedPacketModel.h"

@implementation ICChatViewController (Logic)
// 同步群信息
- (void)synchronizeGroupInfo
{
    NSDictionary *param = @{@"gId":self.group.gId,
                            @"eId":[ICUser currentUser].eId,
                            @"lastUpdate":[ICMessageHelper getGroupInfoLastUpdate:self.group.gId]};
    WEAKSELF
    [[ICSocketRequestManager sharedInstance] groupInfoWithObject:param Success:^(id response) {
        NSDictionary *data = [response objectForKey:@"data"];
        NSDictionary *gInfo = [data objectForKey:@"gInfo"];
        ICGroup *group = [ICGroup mj_objectWithKeyValues:gInfo];
        group.valid = self.group.valid; //  特殊处理valid问题
        [ICMessageDatabase updateGroupInfo:group];
        weakSelf.group = group;
        NSArray *arrs = [data objectForKey:@"gUsers"];
        NSMutableArray *saveUsers = [[NSMutableArray alloc] init];
        NSMutableArray *groupUsers = [[NSMutableArray alloc] init];
        for (NSDictionary *d in arrs) {
            ICGroupUser * groupUser = [[ICGroupUser alloc] init];
            ICUser * gUser   = [ICUser mj_objectWithKeyValues:d];
            if (gUser.valid == 0) {
                [ICMessageDatabase deleteGroupUserWithGroupId:group.gId eId:gUser.eId];
            } else {
                groupUser.eId = gUser.eId;
                groupUser.nName = gUser.nName == nil ? gUser.eName : gUser.nName;
                groupUser.valid = gUser.valid;
                [saveUsers addObject:gUser];
                [groupUsers addObject:groupUser];
//                [ICMessageDatabase saveUser:gUser];
//                [ICMessageDatabase saveGroupUserWithGroupId:group.gId groupUser:groupUser];
            }
        }
        [ICMessageDatabase saveUsers:saveUsers];
        [ICMessageDatabase saveGroupUsersWithGroupId:group.gId groupUsers:groupUsers];
        [ICMessageHelper setGroupInfoLastUpdate:[data objectForKey:@"lastUpdate"] gId:self.group.gId];
    } Failure:^(NSError *error, id other) {
    }];
}

// 加载数据
- (void)loadDataSource
{
    WEAKSELF
    [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:self.group.gId firstMessage:nil finish:^(NSArray *array, NSError *error) {
        if (array.count>0) {
            [weakSelf.dataSource addObjectsFromArray:array];
            
            ICMessageFrame *firstMessage = [array firstObject];
            ICMessageFrame *lastMessage = [array lastObject];
            
            int lastMessageId = [lastMessage.model.message.messageId intValue];
            int firstMessageId = [firstMessage.model.message.messageId intValue];
            NSLog(@"firstMessage: %@ - lastMessage: %@", firstMessage.model.message.messageId, lastMessage.model.message.messageId);
            
            if (lastMessageId - firstMessageId >= LoadMessageCount) {
                NSDictionary *param = @{@"gId":self.group.gId,
                                        @"maxIndex":[NSNumber numberWithInt:lastMessageId],
                                        @"size":@LoadMessageCount};
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) , ^{
                    [[ICSocketRequestManager sharedInstance] repullMessageWithObject:param Success:^(id response) {
                        NSArray *data = [response objectForKey:@"data"];
                        if (data.count > 0) {
                            [weakSelf.dataSource removeAllObjects];
                            for (NSDictionary *dic in data) {
                                
                                [ICMessageHelper messageTypeWithMessage:dic finished:^(ICMessageFrame *messageF) {
                                    [ICMessageDatabase saveMessage:messageF.model];
                                }];
                            }
                            [weakSelf loadNewMessage];
                        }
                    } Failure:^(NSError *error, id other) {
                        NSLog(@"ICRepullAPI request error:%@",error);
                    }];
                });
            }
        } else {
            weakSelf.dataSource = nil;
        }
        [weakSelf.tableView reloadData];
        [weakSelf scrollToBottomAnimated:NO];
    }];
}

- (void)loadNewMessage {
    WEAKSELF
    [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:self.group.gId firstMessage:nil finish:^(NSArray *array, NSError *error) {
        if (array.count>0) {
            [weakSelf.dataSource addObjectsFromArray:array];
            [weakSelf.tableView reloadData];
            [weakSelf scrollToBottomAnimated:YES];
        } else {
            weakSelf.dataSource = nil;
            [weakSelf.tableView reloadData];
        }
    }];
}


- (NSString *)videoPath:(ICMessageFrame *)messageF
{
    NSString *videoPath   = [[ICVideoManager shareManager] videoPathWithFileName:[[messageF.model.mediaPath lastPathComponent] stringByDeletingPathExtension]];
    NSString *mp4Path     = [[videoPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"mp4"];
    return mp4Path;
}

- (NSString *)localFilePath:(ICMessageFrame *)modelFrame
{
    NSString *lnk = modelFrame.model.message.lnk;
    NSDictionary *dicLnk = [NSDictionary dictionaryWithJsonString:lnk];
    NSString *orgName  = [dicLnk objectForKey:@"n"];
    NSString *key      = modelFrame.model.message.fileKey;
    NSString *path = [ICFileTool filePathWithName:key orgName:[[orgName stringByDeletingPathExtension] lastStringSeparatedByString:@"_"] type:[orgName pathExtension]];
    
    return path;
}


#pragma mark - 分享 -- 针对外部分享
- (void)shareContentMessage
{
    if (self.shareContent) {
        ICShareBottomView *bgView = [[ICShareBottomView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height)];
        [[UIApplication sharedApplication].keyWindow addSubview:bgView];
        
        _shareBgView = bgView;
        switch (self.shareContent.shareObject.mediaType) {
            case ICMediaType_Text:
            {
                [self sendTextMessageWithContent:self.shareContent.shareObject.textObject.text];
                break;
            }
            case ICMediaType_Image:
            {
                NSString *orgPath = [[ICMediaManager sharedManager] imagePathWithName:[NSString stringWithFormat:@"%@.png",[NSString currentName]]];
                NSData *imgData = UIImageJPEGRepresentation(self.shareContent.shareObject.imageObject.image, 1.0);
                BOOL result = [imgData writeToFile:orgPath atomically:NO];
                if (!result) NSLog(@"write share image failured");
                [self sendImageMessageWithImgPath:orgPath];
                break;
            }
            case ICMediaType_Video:
            {
                break;
            }
            case ICMediaType_File:
            {
                // 本地是否存在文件 不存在则存储 存储文件
                NSString *fileKey = self.shareContent.shareObject.fileObject.fileKey;
                NSString *extType = self.shareContent.shareObject.fileObject.fileType;
                NSString *fileName = [NSString stringWithFormat:@"%@.%@", self.shareContent.shareObject.fileObject.fileName,self.shareContent.shareObject.fileObject.fileType];
                NSString *path = [ICFileTool filePathWithName:fileKey orgName:[fileName stringByDeletingPathExtension] type:extType];
                
                if (![ICFileTool fileExistsAtPath:path]) {
                    [self.shareContent.shareObject.fileObject.file writeToFile:path atomically:NO];
                }
                [self sendFileMessageWithFileName:[path lastPathComponent]];
                break;
            }
            case ICMediaType_PicURL:
            {
                [self sendPicTextMessageWithContent:self.shareContent.shareObject];
                break;
            }
            default:
                break;
        }
        [self shareSucceed:self.shareContent.shareObject.message.displayName];
        // 发送用户留言
        if (self.shareContent.textFieldStr && self.shareContent.textFieldStr.length>0 && ![self.shareContent.textFieldStr isTrimmingSpace]) {
            [self sendTextMessageWithContent:self.shareContent.textFieldStr];
        }
    }
}

// 分享成功
- (void)shareSucceed:(NSString *)displayName
{
    ICShareSuccessView *succView = [[ICShareSuccessView alloc] initWithFrame:CGRectMake(50, 0, App_Frame_Width-100, 135)];
    succView.centerY = _shareBgView.centerY;
    succView.displayName = displayName;
    [_shareBgView addSubview:succView];
}

/******************* 动态菜单 *********************/
- (void)getMenuItems {
    NSDictionary *param = @{@"gId":self.group.gId,
                            @"lastUpdate":@"0"};
    [[ICChatNetworkManager sharedInstance] getPubMenuWithParam:param requestCache:^(id responseCache) {
        [self setPubMenuObject:responseCache];
    } Success:^(id object) {
        [self setPubMenuObject:object];
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)setPubMenuObject:(id)object {
    
    NSArray *menu = [[object objectForKey:@"data"] objectForKey:@"menu"];
    NSMutableArray *bottomItems = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in menu) {
        ICPubItemModel *model = [ICPubItemModel mj_objectWithKeyValues:dict];
        [bottomItems addObject:model];
    }
    
    self.pubMenuView.bottomItems = bottomItems;
}

/******************* 客服 *********************/
- (void)getCustomers {
    [[ICChatNetworkManager sharedInstance] getCustomerWithParam:nil requestCache:^(id responseCache) {
        [self setCustomersViewObject:responseCache];
    } Success:^(id object) {
        [self setCustomersViewObject:object];
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)setCustomersViewObject:(id)object {
    NSArray *array = [object objectForKey:@"data"];
    NSMutableArray *customs = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in array) {
        ICServerModel *model  = [ICServerModel mj_objectWithKeyValues:dict];
        [customs addObject:model];
    }
    self.transCustomerView.pickerArray = customs;
}

// 获取人员
- (void)loadData
{
    // 发送@消息的前提
    if([self.group.gType integerValue] == ICGroup_GENIUS || [self.group.gType integerValue] == ICGroup_MULTI)
    {
        WEAKSELF
        [ICMessageDatabase getUsersWithGroupId:self.group.gId finish:^(NSArray *array, NSError *error) {
            if (array.count == 0) return;
            weakSelf.users   = (NSMutableArray *)array;
            
        }];
    }else{
        self.users  = nil;
    }
}

/** @ 发送时匹配文本*/
-(void)matching:(NSString *)str
{
    for (NSString * key in self.Mutabledict.allKeys) {
        if ([str rangeOfString:self.Mutabledict[key]].location == NSNotFound) {
            NSLog(@"不包含 value");
            [self.Mutabledict removeObjectForKey:key];
        } else {
            NSLog(@"包含 value");
        }
    }
}

/** @ 草稿匹配文本*/
-(void)thematching:(NSString *)str
{
//    [self loadData];
//
//    if(self.users){
//        for(ICUser *user in self.users){
//            NSString * name = [NSString stringWithFormat:@"%@\u2005",user.nName ==nil ?user.eName:user.nName];
//            if ([str rangeOfString:name].location == NSNotFound) {
//                NSLog(@"不包含 value");
//            } else {
//                NSLog(@"包含 value");
//                [self.Mutabledict setObject:name forKey:user.eId];
//            }
//        }
//    }
    NSString *pattern = @"@(\\w+)\\u2005";        //匹配规则
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
    
    //测试字符串
    NSMutableArray *reguleStrArray = [[NSMutableArray alloc] init];
    NSArray<NSTextCheckingResult *> *results = [regex matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    [results enumerateObjectsUsingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [reguleStrArray addObject:[str substringWithRange:obj.range]];
    }];
    
    for (NSString *name in reguleStrArray) {
        
        NSMutableString *string = [[NSMutableString alloc]initWithString:name];
        NSRange range = NSMakeRange(0, [string length]);
        [string replaceOccurrencesOfString:@"@" withString:@"" options:NSCaseInsensitiveSearch range:range];
        NSRange range1 = NSMakeRange(0, [string length]);
        [string replaceOccurrencesOfString:@"\u2005" withString:@"" options:NSCaseInsensitiveSearch range:range1];
        NSString *eId = [ICMessageDatabase getUsersWithName:[string copy] gId:self.group.gId];
        [self.Mutabledict setObject:[string copy] forKey:eId];
        NSLog(@"%@", string);
        NSLog(@"%@", eId);
    }
}



/** 添加@功能*/
-(void)chooseMembers:(NSDictionary *)dict
{
    NSLog(@"选择的人名字：%@",dict.allValues[0]);
    //8197标识 \u2005
    if(dict.allValues[0] !=nil){
        //NSString *str =[NSString stringWithFormat:@"%@%@",self.textView.text,dict.allValues[0]];
        //self.chatBoxVC.chatBox.textView.text = str;
        [self.textView insertText:dict.allValues[0]];
        NSLog(@"%@",self.textView.text);
        [self.chatBoxVC.chatBox.textView becomeFirstResponder];
        
        [self.Mutabledict setObject:dict.allValues[0] forKey:dict.allKeys[0]];
        NSLog(@"%@", self.Mutabledict);
    }
}

- (void)loadNewData
{
    [self.tableView.mj_header beginRefreshing];
    ICMessageFrame *firstMessageF = [self.dataSource firstObject];
    __weak typeof(self) weakSelf = self;
    [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:self.group.gId firstMessage:firstMessageF.model.message finish:^(NSArray *array, NSError *error) {
        // 如果array是空的，则尝试从网上加载连续的数据
        if (array.count > 0) {
            ICMessageFrame *firstMessageFrame = [array firstObject];
            int firstMessageId = [firstMessageFrame.model.message.messageId intValue];
        
            // 上一组的消息id
            int lastMessageId = [firstMessageF.model.message.messageId intValue];
            
            
            if ((lastMessageId - firstMessageId) > LoadMessageCount) {
                NSDictionary *param = @{@"gId":self.group.gId,
                                        @"maxIndex":[NSNumber numberWithInt:lastMessageId],
                                        @"size":@LoadMessageCount};
                [weakSelf repullMessage:param viewController:weakSelf firstMessageF:firstMessageF];
            }else {
                ICMessageFrame *arrayfirstMessageF = [array firstObject];
                ICMessageFrame * SoureMessageF = [weakSelf.dataSource firstObject];
                if(![arrayfirstMessageF.model.message.messageId isEqualToString:SoureMessageF.model.message.messageId]){
                    [weakSelf.dataSource insertObjects:array atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, array.count)]];
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:array.count inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView.mj_header endRefreshing];
                });
            }
        } else {
            NSLog(@"native no message");
            if (!_isGroupValid){ // group inValid
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView.mj_header endRefreshing];
                });
                return;
            }
            NSString *maxIndex = firstMessageF.model.message.messageId;
            int index = maxIndex.intValue;
            if (maxIndex == nil) {
                NSLog(@"native maxId is %@", maxIndex);
                NSString *groupMaxIndex = self.group.lastMsgId;
                if (groupMaxIndex == nil) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.tableView.mj_header endRefreshing];
                    });
                    return;
                } else {
                    maxIndex = groupMaxIndex;
                }
                NSDictionary *param = @{@"gId":self.group.gId,
                                        @"maxIndex":maxIndex,
                                        @"size":@LoadMessageCount};
                [weakSelf repullMessage:param viewController:weakSelf firstMessageF:firstMessageF];
            }
            else if (index == 0 || index == 1) { // 已经是最后一条了
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView.mj_header endRefreshing];
                });
            } else {
                NSDictionary *param = @{@"gId":self.group.gId,
                                        @"maxIndex":[maxIndex numberValue] == nil ? @0:[maxIndex numberValue],
                                        @"size":@LoadMessageCount};
                [weakSelf repullMessage:param viewController:weakSelf firstMessageF:firstMessageF];
            }
        }
    }];
}

#pragma mark - NetWork

// repull message
- (void)repullMessage:(NSDictionary *)param viewController:(ICChatViewController *)weakSelf firstMessageF:(ICMessageFrame *)firstMessageF
{
    [[ICSocketRequestManager sharedInstance] repullMessageWithObject:param Success:^(id response) {
        // 后台返的消息id是从小到大
        
        NSArray *data = [response objectForKey:@"data"];
        if (data.count > 0) {
            for (NSDictionary *dic in data) {
                
                [ICMessageHelper messageTypeWithMessage:dic finished:^(ICMessageFrame *messageF) {
                    [ICMessageDatabase saveMessage:messageF.model]; // 统一存储消息
                    
                }];
            }
            [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:weakSelf.group.gId firstMessage:firstMessageF.model.message finish:^(NSArray *array, NSError *error) {
                if (array.count > 0) {
                    [weakSelf.dataSource insertObjects:array atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, array.count)]];
                    [weakSelf.tableView reloadData];
                    [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:array.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableView.mj_header endRefreshing];
                });
            }];
            
        } else {
            [weakSelf.tableView.mj_header endRefreshing];
        }
    } Failure:^(NSError *error, id other) {
        NSLog(@"ICRepullAPI request error:%@",error);
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

// 红包
- (void)clickRedPacketTaped:(ICMessageModel *)messageModel {
    if (messageModel.message.deliveryState == ICMessageDeliveryState_Failure) {
        return;
    }
    WEAKSELF
    [MBProgressHUD showProcessingActivityView:App_RootCtr.view];
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"gId":self.group.gId,
                            @"redId":messageModel.message.fileKey};
    // 点击红包
    [[ICRedPacketNetworkManager sharedInstance] clickRedPacketWithParam:param success:^(id object) {
        [MBProgressHUD hideHUDForView:App_RootCtr.view animated:YES];
        //[MBProgressHUD hideAllHUDsForView:App_RootCtr.view animated:YES];
        ICClickRedPacketModel *model = [ICClickRedPacketModel mj_objectWithKeyValues:[object objectForKey:@"data"]];
        [weakSelf clickRedPacketLogic:model messageModel:messageModel groupId:weakSelf.group.gId];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:App_RootCtr.view animated:YES];
        //[MBProgressHUD hideAllHUDsForView:App_RootCtr.view animated:YES];
        [MBProgressHUD showError:error.domain];
    }];
}

- (void)removeAVPlayerFlag {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"avPlayerFlag"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
